package com.sjgtw.cloud.app.riskReporting.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mapbox.geojson.LineString;
import com.mapbox.geojson.Point;
import com.sjgtw.cloud.app.riskReporting.domain.RiskReporting;
import com.sjgtw.cloud.app.riskReporting.domain.RiskTracking;
import com.sjgtw.cloud.app.riskReporting.mapper.RiskReportingMapper;
import com.sjgtw.cloud.app.riskReporting.mapper.RiskTrackingMapper;
import com.sjgtw.cloud.app.riskReporting.service.IRiskReportingService;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.exception.BaseException;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.config.LineStringService;
import com.sjgtw.cloud.service.SystemServerService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.util.TransformUtil;
import com.sjgtw.cloud.web.path.domain.PathPoint;
import com.sjgtw.cloud.web.path.mapper.PathPointMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 风险上报Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-03-17
 */
@Service
public class RiskReportingServiceImpl implements IRiskReportingService
{
    @Autowired
    private RiskReportingMapper riskReportingMapper;
    @Autowired
    private RiskTrackingMapper riskTrackingMapper;
    @Autowired
    private PathPointMapper pathPointMapper;
    @Autowired
    private SystemServerService systemServerService;

    @Autowired
    private RedisService redisService;

    @Autowired
    LineStringService lineStringService;

    /**
     * 查询风险上报
     * 
     * @param id 风险上报主键
     * @return 风险上报
     */
    @Override
    public RiskReporting selectRiskReportingById(Long id)
    {
        return riskReportingMapper.selectRiskReportingById(id);
    }

    /**
     * 查询风险上报列表
     * 
     * @param riskReporting 风险上报
     * @return 风险上报
     */
    @Override
    public List<Map<String,Object>> selectRiskReportingList(RiskReporting riskReporting)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);
        if (user == null) {
            throw new BaseException("登录信息失效，请重新登录");
        }
        Long userId = user.getUserid();
        riskReporting.setCreateUserId(userId);
        return riskReportingMapper.selectRiskReportingList(riskReporting);
    }

    @Override
    public List<Map<String, Object>> selectTaskManagementList(RiskReporting riskReporting) {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);
        if (user == null) {
            throw new BaseException("登录信息失效，请重新登录");
        }
        Long userId = user.getUserid();
        riskReporting.setCreateUserId(userId);
        List<Map<String, Object>> taskList = riskReportingMapper.selectTaskManagementList(riskReporting);

        if(taskList.size() == 0){
            return taskList;
        }
        for (int i = 0; i < taskList.size(); i++) {
            Map<String, Object> taskMap = taskList.get(i);
            if (taskMap.get("distributeUserIds") == null) {
                continue;
            }
            String distributeUserIds = String.valueOf(taskMap.get("distributeUserIds"));
            if (StringUtils.isBlank(distributeUserIds)) {
                continue;
            }
            AjaxResult userResult = systemServerService.getUserByIds(distributeUserIds);
            Map<String, String> userMap = new HashMap<>();
            if (userResult != null) {
                Object object = userResult.get("data");
                if (object != null) {
                    JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                    if (!jsonArray.isEmpty()) {
                        for (int j=0; j<jsonArray.size();j++) {
                            JSONObject json = jsonArray.getJSONObject(j);
                            userMap.put(json.getString("userId"), json.getString("userName"));
                        }
                    }
                }
            }
            String[] distributes = distributeUserIds.split(",");
            String distributeUserNames = "";
            for (String distributeUserId : distributes) {
                distributeUserNames += userMap.get(distributeUserId) + ",";
            }
            taskMap.put("distributeUserNames", reduceComma(distributeUserNames));
            if (taskMap.get("confirmUserIds") == null) {
                continue;
            }
            String confirmUserIds = String.valueOf(taskMap.get("confirmUserIds"));
            AjaxResult userConfirmResult = systemServerService.getUserByIds(confirmUserIds);
            Map<String, String> userConfirmMap = new HashMap<>();
            if (userConfirmResult != null) {
                Object object = userConfirmResult.get("data");
                if (object != null) {
                    JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                    if (!jsonArray.isEmpty()) {
                        for (int j=0; j<jsonArray.size();j++) {
                            JSONObject json = jsonArray.getJSONObject(j);
                            userConfirmMap.put(json.getString("userId"), json.getString("userName"));
                        }
                    }
                }
            }

            if (StringUtils.isNotEmpty(confirmUserIds)) {
                String[] confirms = confirmUserIds.split(",");
                String confirmUserNames = "";
                for (String confirmUserId : confirms) {
                    confirmUserNames += userConfirmMap.get(confirmUserId) + ",";
                }
                taskMap.put("confirmUserNames", reduceComma(confirmUserNames));
            }
        }
        return taskList;
    }

    public static String reduceComma(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        } else {
            if (str.startsWith(",")) {
                str = str.substring(1);
            }

            if (str.endsWith(",")) {
                str = str.substring(0, str.length() - 1);
            }
            return str;
        }
    }

    @Override
    public List<Map<String, Object>> getEmergencyTask(RiskReporting riskReporting) {

        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);
        if (user == null) {
            throw new BaseException("登录信息失效，请重新登录");
        }
        Long userId = user.getUserid();
        List<Map<String, Object>> emergencyTaskList = riskReportingMapper.getEmergencyTask();
        List<Map<String, Object>> result = new ArrayList<>();
        if(emergencyTaskList.size()>0){
            for (int i = 0; i < emergencyTaskList.size(); i++) {

                String distributeUserIds = String.valueOf(emergencyTaskList.get(i).get("distributeUserIds"));

                if(StringUtils.isNotBlank(distributeUserIds)){

                    String[] split = distributeUserIds.split(",");
                    List list = CollectionUtils.arrayToList(split);
                    if(list.contains(String.valueOf(userId)) || "admin".equals(user.getUsername())){
                        result.add(emergencyTaskList.get(i));
                    }
                }
            }
        }

        return result;
    }

    @Override
    public int taskDistribute(JSONObject jsonObject) {
        Long id = jsonObject.getLong("id");
        String distributeUserIds = jsonObject.getString("distributeUserIds");

        RiskReporting riskReporting = riskReportingMapper.selectRiskReportingById(id);
        riskReporting.setDistributeUserIds(distributeUserIds);
        riskReporting.setStatus(2);// 已下发

        return  riskReportingMapper.updateRiskReporting(riskReporting);

    }

    @Override
    public int confirmTask(Long id) {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);
        if (user == null) {
            throw new BaseException("登录信息失效，请重新登录");
        }

        RiskReporting riskReporting = riskReportingMapper.selectRiskReportingById(id);
        String confirmUserIds = riskReporting.getConfirmUserIds();
        if (confirmUserIds == null || confirmUserIds.length() == 0) {
            riskReporting.setConfirmUserIds(user.getUserid()+"");
        } else {
            String[] userIds = confirmUserIds.split(",");
            for (String userId : userIds) {
                if ((user.getUserid()+"").equals(userId)) {
                    return 1;
                }
            }
            riskReporting.setConfirmUserIds(confirmUserIds + "," + user.getUserid());
        }

        return  riskReportingMapper.updateRiskReporting(riskReporting);
    }

    @Override
    public int finishTask(Long id) {
        RiskReporting riskReporting = riskReportingMapper.selectRiskReportingById(id);
        riskReporting.setStatus(3);// 处置完成

        return  riskReportingMapper.updateRiskReporting(riskReporting);
    }

    @Override
    public List<Map<String, Object>> getTaskDistributeUser(Long id) {
        RiskReporting riskReporting = riskReportingMapper.selectRiskReportingById(id);

        List<Map<String, Object>> taskDistributeUser = null;
        if(StringUtils.isNotBlank(riskReporting.getDistributeUserIds())){

            String[] split = riskReporting.getDistributeUserIds().split(",");
            taskDistributeUser = riskReportingMapper.getTaskDistributeUser(split);
        }

        return taskDistributeUser;
    }

    /**
     * 新增风险上报
     * 
     * @param riskReporting 风险上报
     * @return 结果
     */
    @Override
    public int insertRiskReporting(RiskReporting riskReporting)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);
        if (user == null) {
            throw new BaseException("登录信息失效，请重新登录");
        }
        riskReporting.setCreateUserId(user.getUserid());
        riskReporting.setCreateBy(user.getSysUser().getUserName());
        riskReporting.setCreateTime(DateUtils.getNowDate());
        setLngLat(riskReporting);
        return riskReportingMapper.insertRiskReporting(riskReporting);
    }

    /**
     * 修改风险上报
     * 
     * @param riskReporting 风险上报
     * @return 结果
     */
    @Override
    public int updateRiskReporting(RiskReporting riskReporting)
    {
        riskReporting.setUpdateTime(DateUtils.getNowDate());
        setLngLat(riskReporting);
        return riskReportingMapper.updateRiskReporting(riskReporting);
    }

    private void setLngLat(RiskReporting riskReporting) {
        if (riskReporting.getMileage() == null || riskReporting.getMileage().length() == 0) {
            return;
        }
        String[] mileages = riskReporting.getMileage().split(",");
        if (mileages.length != 4) {
            return;
        }
        LineString lineString = lineStringService.getLineString();
        Point point1 = TransformUtil.transformSectionToLonLat(lineString, mileages[0], mileages[1]);
        Point point2 = TransformUtil.transformSectionToLonLat(lineString, mileages[2], mileages[3]);
        riskReporting.setLng1(String.valueOf(point1.longitude()));
        riskReporting.setLat1(String.valueOf(point1.latitude()));
        riskReporting.setLng2(String.valueOf(point2.longitude()));
        riskReporting.setLat2(String.valueOf(point2.latitude()));
    }

    /**
     * 批量删除风险上报
     * 
     * @param ids 需要删除的风险上报主键
     * @return 结果
     */
    @Override
    public int deleteRiskReportingByIds(Long[] ids)
    {
        return riskReportingMapper.deleteRiskReportingByIds(ids);
    }

    /**
     * 删除风险上报信息
     * 
     * @param id 风险上报主键
     * @return 结果
     */
    @Override
    public int deleteRiskReportingById(Long id)
    {
        return riskReportingMapper.deleteRiskReportingById(id);
    }

    @Override
    public int track(RiskTracking riskTracking) {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);
        Long userId = user.getUserid();
        String username = user.getUsername();

        RiskTracking param = new RiskTracking();
        param.setRiskId(riskTracking.getRiskId());
        param.setCreateUserId(user.getUserid());
        RiskTracking tracking = riskTrackingMapper.selectRiskTracking(param);

        if (tracking != null) {
            tracking.setLongitude(riskTracking.getLongitude());
            tracking.setLatitude(riskTracking.getLatitude());
            tracking.setUpperId(riskTracking.getUpperId());
            tracking.setPathId(riskTracking.getPathId());
            tracking.setUpdateBy(username);
            tracking.setUpdateTime(DateUtils.getNowDate());
            return riskTrackingMapper.updateRiskTracking(tracking);
        }
        riskTracking.setUserId(userId);
        riskTracking.setCreateUserId(userId);
        riskTracking.setCreateBy(username);
        riskTracking.setCreateTime(DateUtils.getNowDate());
        return riskTrackingMapper.insertRiskTracking(riskTracking);
    }

    @Override
    public RiskTracking getMyTrack(Long riskId) {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);
        if (user == null) {
            throw new BaseException("登录信息失效，请重新登录");
        }
        RiskTracking riskTracking = new RiskTracking();
        riskTracking.setRiskId(riskId);
        riskTracking.setCreateUserId(user.getUserid());
        return riskTrackingMapper.selectRiskTracking(riskTracking);
    }

    @Override
    public List<RiskTracking> getTracksByRiskIdWithRealLocation(Long riskId) {
        RiskTracking riskTracking = new RiskTracking();
        riskTracking.setRiskId(riskId);
        return riskTrackingMapper.selectListWithRealLocation(riskTracking);
    }

    @Override
    public List<RiskTracking> getTracksByRiskId(Long riskId) {
        RiskTracking riskTracking = new RiskTracking();
        riskTracking.setRiskId(riskId);
        return riskTrackingMapper.selectRiskTrackingList(riskTracking);
    }

    public static boolean isDouble(String str) {
        try {
            double value = Double.parseDouble(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    @Override
    public List<Map<String, Object>> screenList() {
        List<Map<String, Object>> maps = riskReportingMapper.screenList();

        if(maps.size()>0){
            for (int i = 0; i < maps.size(); i++) {
                String mileage = String.valueOf(maps.get(i).get("mileage"));
                StringBuilder sb = new StringBuilder();
                String[] split = mileage.split(",");
                if(split.length == 4){
                    sb.append("K");
                    sb.append(split[0]);
                    sb.append("+");
                    sb.append(split[1]);
                    sb.append(",");
                    sb.append("K");
                    sb.append(split[2]);
                    sb.append("+");
                    sb.append(split[3]);
                }
                maps.get(i).put("mileage",sb.toString());

            }
        }

        return maps;
    }

    @Override
    public Map<String, Object> emergencyScreenDetail(Long id) {
        Map<String, Object> map = riskReportingMapper.screenDetail(id);

        String mileage = String.valueOf(map.get("mileage"));
        StringBuilder sb = new StringBuilder();
        String[] split = mileage.split(",");
        if(split.length == 4){
            sb.append("K");
            sb.append(split[0]);
            sb.append("+");
            sb.append(split[1]);
            sb.append(",");
            sb.append("K");
            sb.append(split[2]);
            sb.append("+");
            sb.append(split[3]);
        }
        map.put("mileage",sb.toString());

        RiskTracking riskTracking = new RiskTracking();
        riskTracking.setRiskId(id);
        List<RiskTracking> trackings = riskTrackingMapper.selectListWithRealLocation(riskTracking);
        for (RiskTracking tracking : trackings) {
            PathPoint pathPoint = new PathPoint();
            pathPoint.setPathId(tracking.getPathId());
            List<PathPoint> points = pathPointMapper.selectPathPointList(pathPoint);
            tracking.setPathPoints(points);
        }
        map.put("personList", trackings);
        return map;
    }

}
